package com.duobaoyu.dby.supply.biz.service.rule;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName RuleService
 * @Description 规则Service
 * @createTime 21:37:00 2021/08/22
 */
@Slf4j
public class RuleService {
    private Map<Integer, List<IRuleExecute>> hashMap = new HashMap<>();
    private static final int AND = 1;
    private static final int OR = 0;

    public static RuleService create() {
        return new RuleService();
    }


    public RuleService and(List<IRuleExecute> ruleList) {
        hashMap.put(AND, ruleList);
        return this;
    }

    public RuleService or(List<IRuleExecute> ruleList) {
        hashMap.put(OR, ruleList);
        return this;
    }

    public boolean execute(BaseRule rule) {
        for (Map.Entry<Integer, List<IRuleExecute>> item : hashMap.entrySet()) {
            List<IRuleExecute> ruleList = item.getValue();
            switch (item.getKey()) {
                case AND:
                    // 如果是 and 关系，同步执行
                    if(log.isDebugEnabled()) {
                        log.debug("execute key = " + 1);
                    }
                    if (!this.and(rule, ruleList)) {
                        return false;
                    }
                    break;
                case OR:
                    // 如果是 or 关系，并行执行
                    if(log.isDebugEnabled()) {
                        log.debug("execute key = " + 0);
                    }
                    if (!this.or(rule, ruleList)) {
                        return false;
                    }
                    break;
                default:
                    break;
            }
        }
        return true;
    }

    private boolean and(BaseRule rule, List<IRuleExecute> ruleList) {
        for (IRuleExecute baseRule : ruleList) {
            boolean execute = baseRule.execute(rule);
            if (!execute) {
                // and 关系匹配失败一次，返回 false
                return false;
            }
        }
        // and 关系全部匹配成功，返回 true
        return true;
    }

    private boolean or(BaseRule rule, List<IRuleExecute> ruleList) {
        for (IRuleExecute baseRule : ruleList) {
            boolean execute = baseRule.execute(rule);
            if (execute) {
                // or 关系匹配到一个就返回 true
                return true;
            }
        }
        // or 关系一个都匹配不到就返回 false
        return false;
    }
}
